<template>
  <div class="app-container">
    <el-card style="border-radius: 10px;">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="orderCode">
        <el-input
          v-model="queryParams.orderCode"
          placeholder="请输入订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>


      <!--      <el-form-item label="交货日期" prop="deadline">
              <el-date-picker clearable
                v-model="queryParams.deadline"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择交货日期">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="生产商编码" prop="manufactureCode" label-width="90px">
              <el-input
                v-model="queryParams.manufactureCode"
                placeholder="请输入生产商编码"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>-->
      <el-form-item label="生产商名称" prop="manufactureName" label-width="90px">
        <el-input
          v-model="queryParams.manufactureName"
          placeholder="请输入生产商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!--
            <el-form-item label="产品编号" prop="productCode">
              <el-input
                v-model="queryParams.productCode"
                placeholder="请输入产品编号"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
            <el-form-item label="产品名称" prop="productName">
              <el-input
                v-model="queryParams.productName"
                placeholder="请输入产品名称"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>


            <el-form-item label="订单状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择订单状态" clearable>
                <el-option label="请选择字典生成" value="" />
              </el-select>
            </el-form-item>
      -->

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    </el-card>
    <el-card style="border-radius: 10px;margin-top: 15px">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pro:outsourcingorder:add']"
        >新增
        </el-button>
      </el-col>
      <!--      <el-col :span="1.5">
              <el-button
                type="warning"
                plain
                icon="el-icon-download"
                size="mini"
                @click="handleExport"
                v-hasPermi="['pro:outsourcingorder:export']"
              >导出</el-button>
            </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="orderList" @selection-change="handleSelectionChange">
      <el-table-column label="订单编号" align="center" prop="orderCode">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleInfoView(scope.row)">{{ scope.row.orderCode }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="外协类型" width="120" align="center" prop="outsourceType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.mes_outsource_type" :value="scope.row.outsourceType"/>
        </template>
      </el-table-column>
      <el-table-column label="需求截至日期" align="center" prop="deadline" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deadline, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="生产商编码" align="center" prop="manufactureCode"/>
      <el-table-column label="生产商名称" align="center" prop="manufactureName"/>

      <el-table-column label="付款类型" align="center" prop="paymentType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.erp_payment_type" :value="scope.row.paymentType"/>
        </template>
      </el-table-column>
      <el-table-column label="订单状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-tag type="primary" v-show="scope.row.status==0&&scope.row.approvalStatus==null" dffect="dark">草稿
          </el-tag>
          <!--          <el-tag type="danger" v-show="scope.row.approvalStatus<0" dffect="dark">驳回</el-tag>-->
          <!--          <el-tag type="warning" v-show="scope.row.status!=1&&scope.row.approvalStatus>=0&&scope.row.approvalStatus<scope.row.totalStep" dffect="dark">-->
          <!--            {{ scope.row.statusWords }}</el-tag>-->
          <el-tag type="primary" v-show="scope.row.status==1" dffect="dark">待执行</el-tag>
          <el-tag type="success" v-show="scope.row.status==2" dffect="dark">已执行</el-tag>
          <el-tag type="warning" v-show="scope.row.status==3" dffect="dark">待审批</el-tag>
          <el-tag type="danger" v-show="scope.row.status==4" dffect="dark">已驳回</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="成本" align="center" prop="estimatedCost"/>
      <el-table-column label="操作" width="280px" align="center">
        <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-view"
              @click="handleInfoView(scope.row)"
              v-hasPermi="['pro:outsourcingorder:query']"
            >查看</el-button>
            <el-button
              size="mini"
              type="text"
              v-if="(scope.row.status === 0 || scope.row.status === 4)&&(scope.row.approvalStatus==null||scope.row.approvalStatus<0)"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['pro:outsourcingorder:edit']"
            >修改</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-upload"
              v-if="scope.row.status ==1&&scope.row.outsourceType=='Z'"
              @click="handleUploadFile(scope.row)"
              v-hasPermi="['pro:outsourcingorder:uploadFile']"
            >上传附件</el-button>
            <el-button size="mini" type="text" icon="el-icon-circle-check" @click="handleInfoConfirm(scope.row)"
                       v-if="(scope.row.status === 0 || scope.row.status === 4)&&(scope.row.approvalStatus==null||scope.row.approvalStatus<0)"
                       v-hasPermi="['pro:outsourcingorder:confirm']">确认订单</el-button>
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['pro:outsourcingorder:remove']"
              v-if="(scope.row.status === 0 || scope.row.status === 4)&&(scope.row.approvalStatus==null||scope.row.approvalStatus<0)"
            >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>
    <!-- 添加或修改订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body>
      <el-tabs type="border-card" v-model="activeTab">
        <el-tab-pane :key="1" label="订单信息" name="订单信息">
          <!--          <div style="font-size: 20px;">订单信息</div>-->
          <!--          &lt;!&ndash;横线组件纯纯为了页面好看&ndash;&gt;-->
          <!--          <el-divider></el-divider>-->
          <el-form ref="form" :model="form" :rules="rules" label-width="110px"
                   :disabled="optType == 'view'||optType=='upload' || optType == 'confirm'">
            <el-row>
              <el-col :span="12">
                <el-form-item label="订单编号" prop="orderCode">
                  <el-input v-model="form.orderCode" placeholder="请输入订单编号" :readonly="optType != 'save'"/>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="订单名称" prop="orderName">
                  <el-input v-model="form.orderName"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="外协类型" prop="outsourceType">
                  <el-select v-model="form.outsourceType" :disabled="optType!='save'" placeholder="请选择外协订单类型" @change="outsourceTypeChange">
                    <el-option
                      v-for="dict in dict.type.mes_outsource_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="dict.value"

                    ></el-option>
                  </el-select>
                </el-form-item>

              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item style="width: 100%" label="需求截至日期" prop="deadline">
                                <el-date-picker clearable
                                                v-model="form.deadline"
                                                type="date"
                                                value-format="yyyy-MM-dd"
                                                placeholder="请选择需求截至日期">
                                </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="付款方式" prop="paymentType">
                  <el-select v-model="form.paymentType" placeholder="请选择付款类型" clearable>
                    <el-option
                      v-for="dict in dict.type.erp_payment_type"
                      :key="dict.value"
                      :label="dict.label"
                      :value="parseInt(dict.value)"/>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="生产商编码" prop="manufactureCode">
                  <el-input v-model="form.manufactureCode" placeholder="请选择生产商" readonly>
                    <el-button slot="append" icon="el-icon-search" @click="handleManufactureSelect"></el-button>
                  </el-input>
                  <SelectManufacture ref="mfSelect" :oldManufactureId="form.manufactureId" :manufacture="manufacture"
                                     @onSelected="onManufactureSelected"></SelectManufacture>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="生产商名称" :disabled="true" prop="manufactureName">
                  <el-input v-model="form.manufactureName" :disabled="true"/>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="联系人" prop="contact">
                  <el-input v-model="form.contact" :disabled="true"/>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系人电话" prop="contactTel">
                  <el-input v-model="form.contactTel" :disabled="true"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="采购人员" prop="buyer">
                  <el-input v-model="form.buyer" placeholder="请选择采购人员" readonly>
                    <el-button
                      slot="append"
                      @click="handleSelectUser"
                      icon="el-icon-search">
                    </el-button>
                  </el-input>
                  <UserSelect ref="userSelect" @onSelected="onUserSelected"></UserSelect>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="采购部门" prop="buyerDept">
                  <el-input v-model="form.buyerDept" readonly/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="成本" prop="estimatedCost2">
                  <el-input v-model="form.estimatedCost2" :disabled="true"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="外协合同" prop="drawUrl">
                  <FileUpload
                    :limit="1"
                    :fileSize="100"
                    :fileType="fileType"
                    :value="pictureList"
                    :optType="optType"
                    :isShowTip="isShowTip"
                    @onUploaded="handleUploaded"
                    @onRemoved="handleRemoved"
                    v-if="optType == 'edit'||optType=='save'"
                  >
                  </FileUpload>
                  <li :key="form.drawUrl"
                      v-if="optType != 'edit'&&optType!='save'&&form.drawUrl!=null&&form.drawUrl!=''"
                      class="el-upload-list__item ele-upload-list__item-content">
                    <el-link :href="`${form.drawUrl}`" v-if="form.drawUrl!=null" :underline="false" target="_blank">
                      <span class="el-icon-document"> {{ getFileName(form.drawUrl) }} </span>
                    </el-link>
                  </li>
                  <el-input v-model="form.drawUrl" v-show="false"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item label="备注" prop="remark">
                  <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
                </el-form-item>
              </el-col>
            </el-row>

          </el-form>
          <el-divider content-position="center">订单产品信息</el-divider>
         <el-tabs type="border-card" v-model="activeTab2">
           <el-tab-pane label="订单产品信息" name="first" >
               <el-row :gutter="10" class="mb8" >
                 <el-col :span="1.5">
                   <el-button
                     type="primary"
                     plain
                     icon="el-icon-plus"
                     size="mini"
                     @click="selectPlanProduct"
                     v-if="optType == 'save' || optType == 'edit'"
                     v-hasPermi="['pro:outsourcingorder:add']"
                   >新增</el-button>
                 </el-col>
               </el-row>

               <el-table  border v-loading="loading" :data="productList" >
                 <el-table-column label="计划编号" align="center" prop="planNo" width="150"/>
                 <el-table-column label="产品编号" align="center" prop="productCode"width="150" >
                 </el-table-column>
                 <el-table-column v-if="form.outsourceType=='G'" label="工序编号" align="center" prop="processCode" width="150"/>
                 <el-table-column v-if="form.outsourceType=='G'" label="工序名称" align="center" prop="processName" width="150"/>
                 <el-table-column  v-if="form.outsourceType=='G'"  label="是否质检" align="center" prop="needCheck" fixed="right" width="100">
                   <template slot-scope="scope">
                     <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.needCheck"/>
                   </template>
                 </el-table-column>
                 <el-table-column label="产品名称" align="center" prop="productName">
                   <template slot-scope="scope">
                     {{scope.row.productName}}
                   </template>
                 </el-table-column>
                 <el-table-column label="规格型号" align="center" prop="specification" width="100">
                   <template slot-scope="scope">
                     {{scope.row.specification}}
                   </template>
                 </el-table-column>
                 <el-table-column label="图纸" v-if="optType=='upload'" align="center" prop="drawingCount" width="100">
                   <template slot-scope="scope">
                     <el-button size="mini" type="text"  @click="openDrawing(scope.row)"  v-if="scope.row.drawingCount>0">
                       {{scope.row.drawingCount}}
                     </el-button>
                   </template>
                 </el-table-column>
                 <el-table-column label="单位" align="center" prop="unitOfMeasure" width="100"/>
                 <el-table-column
                   v-for="col in columnsConfig"
                   :key="col.prop"
                   :label="col.label"
                   :prop="col.prop"
                   :width="col.width"
                   :align="col.align"
                   v-if="col.show">
                 </el-table-column>
                 <el-table-column label="需求数量" align="center"v-if="form.outsourceType=='G'"  prop="productQuantity" fixed="right" width="150">
                   <template slot-scope="scope">
                     <el-input-number
                       :min="0.01"
                       :step="0.01"
                       :precision="2"
                       type="number"
                       size="mini"
                       v-model="scope.row.productQuantity"
                       @blur="getTotalPrice2(scope.row)"
                       @change="getTotalPrice2(scope.row)"
                       v-if="(optType == 'save' || optType == 'edit')"
                     />

                     <span  v-if="(optType != 'save' && optType != 'edit')">{{scope.row.productQuantity}}</span>
                   </template>
                 </el-table-column>
                 <el-table-column label="需求数量" align="center" v-if="form.outsourceType=='Z'"  prop="productQuantity" fixed="right" width="150">
                   <template slot-scope="scope">
                     <el-input-number
                       :min="0.01"
                       :step="0.01"
                       :precision="2"
                       type="number"
                       size="mini"
                       v-model="scope.row.productQuantity"
                       v-if="(optType == 'save' || optType == 'edit')"
                     />
                     <span  v-if="(optType != 'save' && optType != 'edit')">{{scope.row.productQuantity}}</span>
                   </template>
                 </el-table-column>
                 <el-table-column label="单价" align="center"v-if="form.outsourceType=='G'"  prop="price" fixed="right" width="150">
                   <template slot-scope="scope">
                     <el-input-number
                       :min="0.01"
                       size="mini"
                       :step="0.01"
                       :precision="2"
                       style="width: 120px"
                       v-model="scope.row.price"
                       v-if="(optType == 'save' || optType == 'edit')"
                       @blur="getTotalPrice2(scope.row)"
                       @change="getTotalPrice2(scope.row)"
                     >
                     </el-input-number>
                     <span    v-if="(optType != 'save' && optType != 'edit')">{{scope.row.price}}</span>
                   </template>
                 </el-table-column>
                 <el-table-column label="产品总价" align="center" v-if="form.outsourceType=='G'" prop="totalPrice" width="80" fixed="right">
                   <template slot-scope="scope">
                     {{scope.row.totalPrice}}
                   </template>
                 </el-table-column>
                 <el-table-column
                   fixed="right"
                   label="操作"
                   align="center"
                   class-name="small-padding fixed-width"
                   v-if="optType == 'save' || optType == 'edit' || optType == 'select'||optType=='upload'">
                   <template slot-scope="scope">
                     <el-button
                       size="mini"
                       type="text"
                       icon="el-icon-delete"
                       v-if="optType == 'save' || optType == 'edit'"
                       @click="handleDeleteLine(scope.row)"
                     >删除</el-button>
                     <el-button
                       size="mini"
                       type="text"
                       icon="el-icon-upload"
                       v-if="optType == 'upload'"
                       @click="openDrawing(scope.row)"
                     >附件上传</el-button>
                   </template>
                 </el-table-column>
               </el-table>

           </el-tab-pane>
           <el-tab-pane label="产品信息合计" v-if="form.outsourceType=='Z'" name="heji">
             <el-table border v-loading="loading" :data="productList2" >
               <el-table-column label="产品编号" align="center" prop="productCode"width="150" >
               </el-table-column>
               <el-table-column label="产品名称" align="center" prop="productName" width="150"/>
               <el-table-column label="规格型号" align="center" prop="specification" width="100"/>
               <el-table-column label="单位" align="center" prop="unitOfMeasure" width="100"/>
               <el-table-column label="是否质检" align="center" prop="needCheck"  width="100">
                 <template slot-scope="scope">
                   <el-switch  v-model="scope.row.needCheck" :disabled="optType!='save'&&optType!='edit'"
                   active-value="Y" active-text="是" inactive-value="N" inactive-text="否"
                   ></el-switch>
                 </template>
               </el-table-column>
               <el-table-column label="需求数量" align="center" prop="productQuantity" width="100">
               </el-table-column>
               <el-table-column label="单价" align="center" prop="price" width="150">
                 <template slot-scope="scope">
                   <el-input-number
                     :min="0.01"
                     size="mini"
                     :step="0.01"
                     :precision="2"
                     style="width: 120px"
                     v-model="scope.row.price"
                     v-if="(optType == 'save' || optType == 'edit')"
                     @blur="getTotalPrice(scope.row)"
                     @change="getTotalPrice(scope.row)"
                   >
                   </el-input-number>
                   <span  v-if="(optType != 'save' && optType != 'edit')">{{scope.row.price}}</span>
                 </template>
               </el-table-column>
               <el-table-column label="产品总价" align="center" prop="totalPrice" width="80" >
                 <template slot-scope="scope">
                   {{scope.row.totalPrice}}
                 </template>
               </el-table-column>
               <el-table-column label="BOM编码" align="center" prop="bomCode" width="150"  v-if="form.outsourceType=='Z'">
               </el-table-column>
               <el-table-column label="工艺路线编码" align="center" prop="routeCode" width="100"  v-if="form.outsourceType=='Z'">
               </el-table-column>
               <el-table-column label="工艺路线名称" align="center" prop="routeName" width="150"  v-if="form.outsourceType=='Z'">
               </el-table-column>
               <!--          <el-table-column label="预估产品总价" align="center" prop="totalCost" />-->
               <el-table-column
                 fixed="right"
                 label="操作"
                 align="center"
                 class-name="small-padding fixed-width"
                 v-if="optType == 'save' || optType == 'edit' || optType == 'select'">
                 <template slot-scope="scope">
                   <el-button
                     size="mini"
                     type="text"
                     v-if="(optType == 'save' || optType == 'edit')"
                     @click="handleSelectBom(scope.row)"
                   >选择产品制程</el-button>
                 </template>
               </el-table-column>
             </el-table>
             <PlanningBomItemSelect
               ref="bomItemSelect"
               :product-id="bomRow.productId"
               :planning="bomRow"
               @onSelected="onBomItemSelected"
               v-if="bomShowFlag"
             ></PlanningBomItemSelect>
           </el-tab-pane>
         </el-tabs>
         <plan-product-selector :selectedList="productList":needAddProductList="needAddProductList" :outsource-type="form.outsourceType" :show-dialog="showFlag" v-if="showFlag" @onSelected="onProductSelected" @cancelSelectProduct="cancelSelectProduct" ></plan-product-selector>

        </el-tab-pane>
        <el-tab-pane :key="2" label="审批流程" v-if=" optType!='save' && this.form.instanceId ">
          <el-timeline id="approveTimeLine">
            <el-timeline-item
              v-for="item in approveFlow"
              :key="item.id"
              :timestamp="item.updateTime"
              placement="top"
              icon="el-icon-success"
              color="#13ce66"
            >
              <el-card>
                <h3>{{ item.nodeName }}
                  <b>{{ item.approver }}</b>
                  <span
                    style="font-weight:800;"
                    :style="{ color: item.skipType === 'PASS' ? 'green' : 'red' }">
                  {{ item.skipType === 'PASS' ? '同意' : '驳回' }}
                </span>
                </h3>
                <p style="padding-top: 20px;">审批意见：{{ item.message }}</p>
              </el-card>
            </el-timeline-item>
          </el-timeline>
        </el-tab-pane>
        <el-tab-pane label="审批图" name="审批图" v-if=" optType!='save' && this.form.instanceId">
          <img :src="imgUrl" width="100%" style="margin:0 auto"/>
        </el-tab-pane>
      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" v-if="optType == 'confirm'" @click="confirmOrderFun">确认订单</el-button>
        <el-button type="primary" v-if="optType == 'save'||optType=='edit'" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <Drawing ref="drawing" :orderLineId="orderLineId" @close="refreshLine"></Drawing>
  </div>
</template>

<script>
import {
  listOrder,
  getOrder,
  delOrder,
  addOrder,
  updateOrder,
  executeOrder,
  listLine,
  confirmOrder, approveFlow, listApproveOrder
} from "@/api/mes/pro/outsourcingorder";
import {genCode} from '@/api/system/autocode/rule';
import SelectManufacture from "@/views/mes/md/outsourcedmanufacture/selectManufacture.vue";
import FileUpload from "@/components/FileUpload/index.vue";
import SourceSelect from "@/components/sourceSelect/single.vue";
import OrderLine from "@/views/mes/pro/outsourcingorder/orderLine.vue";
import PlanLine from "@/views/mes/pro/outsourcingplan/planline.vue";
import Planselector from "@/views/mes/pro/outsourcingplan/planselector.vue";
import {copyValues} from "@/utils/ruoyi";
import UserSelect from "@/components/userSelect/single.vue";
import Template from "@/views/print/printtemplate/list.vue";
import PlanProductSelector from "@/views/mes/pro/outsourcingplan/planProductSelector.vue";
import PlanningBomItemSelect from '@/components/proPlanningBomSelect/single.vue';
import Drawing from "@/views/mes/pro/outsourcingorder/drawing.vue";
import {getColumnsConfigKey} from "@/api/system/columnsconfig";
export default {
  name: "Order",
  components: {
    Template,
    PlanLine,
    OrderLine,
    SourceSelect,
    SelectManufacture,
    FileUpload,
    Planselector,
    UserSelect,
    PlanProductSelector,
    PlanningBomItemSelect,
    Drawing,
  },
  dicts: ['erp_payment_type', 'mes_outsource_order_status', 'mes_outsource_type','mes_workorder_sourcetype','sys_yes_no'],
  data() {
    return {
      columnsConfig:[],
      orderLineId:null,
      needAddProductList: new Map(),
      bomRow:null,
      bomShowFlag:false,
      productList:[],
      productList2:[],
      activeTab: '订单信息',
      activeTab2:'first',
      approveForm: {},
      approveFlow: [{}],
      planLineOptType: 'view',
      planLineList: [],
      fileType: ["pdf"],
      // 图纸列表
      pictureList: [],
      // 上传提示开关
      isShowTip: true,
      manufacture: {enableFlag: 'Y', manufactureId: null},
      imgUrl: '',
      optType: 'view',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      orderList: [],
      orderLine: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      showFlag: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: null,
        deadline: null,
        manufactureId: null,
        manufactureCode: null,
        manufactureName: null,
        contact: null,
        contactTel: null,
        paymentType: null,
        status: null
      },
      // 表单参数
      form: {
        id: null, orderCode: null,
        orderName: null, deadline: null,
        manufactureId: null, manufactureCode: null,
        manufactureName: null,
        contact: null, contactTel: null,
        paymentType: null, status: 0,
        remarks: null,
        estimatedCost: null,
        estimatedCost2: null,
        createBy: null, createTime: null, updateBy: null, updateTime: null, drawUrl: null, tenantId: null,
        sourceCode: null,
        planNo: null,
        requestDate: null,
        outsourceType:'Z'
      },
      // 表单校验
      rules: {
        orderCode: [
          {required: true, message: "订单编号不能为空", trigger: "blur"}
        ],
        outsourceType: [
          {required: true, message: "外协订单类型不能为空", trigger: "blur"}
        ],
        deadline: [
          {required: true, message: "需求截至日期不能为空", trigger: "blur"}
        ],
        paymentType: [
          {required: true, message: "付款方式不能为空", trigger: "blur"}
        ],
        manufactureCode: [
          {required: true, message: "生产商编码不能为空", trigger: "blur"}
        ],
        planNo: [
          {required: true, message: "生产计划不能为空", trigger: "blur"}
        ],
        manufactureName: [
          {required: true, message: "生产商名称不能为空", trigger: "blur"}
        ],
        estimatedCost2: [
          {required: true, message: "成本不能为空", trigger: "blur"}
        ],
        buyer: [
          {required: true, message: "采购员不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getItemBase();
  },
  watch: {
    productList: {
      handler(newVal, oldVal) {
        if(newVal.length == 0&&this.form.outsourceType=='Z'){
          this.productList2=[];
        }
        else if (newVal.length > 0&&this.form.outsourceType=='Z') {
          const result = Array.from(
            this.productList.reduce((map, item) => {
              let a = {
                productCode: item.productCode,
                productId: item.productId, productName: item.productName, specification: item.specification,
                unitOfMeasure: item.unitOfMeasure,

              }
              const b = JSON.stringify(a);
              const val = map.get(b) || { productQuantity: 0.00};
              val.price = item.price || 0.01;
              this.copy6(item, val)
              val.productQuantity = val.productQuantity + item.productQuantity;
              val.totalPrice = Math.round(val.price * val.productQuantity * 100) / 100;

              map.set(b, val);
              return map;
            }, new Map())
          ).map(([key, value]) => {
            return {
              ...JSON.parse(key),
              ...value
            };
          });
          if (this.productList2.length > 0) {
            result.forEach(item => {
              item.productQuantity=Math.round( item.productQuantity * 100) / 100;
              let r = this.productList2.find((item2) => item2.productCode == item.productCode)
              if (r) {
                item.routeCode = r.routeCode;
                item.routeName = r.routeName;
                item.routeId = r.routeId;
                item.bomCode = r.bomCode;
                item.bomName = r.bomName;
                item.bomId = r.bomId;
                item.needCheck=r.needCheck;
                if (r.price) {
                  item.price = r.price;
                  item.totalPrice = Math.round(item.price * item.productQuantity * 100) / 100;
                }
              }
            })
          }
          this.productList2 = result;
          this.getEstimatedCost(result)
        }
      },
      deep: true
    }
  },
  methods: {
    getItemBase(){
      getColumnsConfigKey('MdItem_Base').then(res=>{
        this.columnsConfig = JSON.parse(res.data);
        console.log(this.columnsConfig)
      })
    },
    openDrawing(row){
      this.orderLineId=row.id
      this.$refs.drawing.showFlag=true;
    },
    handleSelectBom(row){
      this.bomRow=row;
      this.bomRow.productSpc=row.specification;
      this.bomShowFlag=true;
      this.$nextTick(() => {
        // 子组件已经渲染完成
        this.$refs.bomItemSelect.showFlag = true;
      })

    },
    //bom选择
    onBomItemSelected(obj) {
      if (obj != undefined && obj != null) {
        this.copy6(obj,this.bomRow)
      }
    },
    copy6(source,target){
      target.bomId = source.bomId;
      target.bomName = source.bomName;
      target.bomCode = source.bomCode;
      target.routeCode=source.routeCode;
      target.routeName=source.routeName;
      target.routeId=source.routeId;
      target.needCheck=source.needCheck||'Y';

    },
    getTotalPrice(row){
      if(row.price!=null&&row.price!=''&&row.productQuantity!=null&&row.productQuantity!=''){
        row.totalPrice = Math.round(row.productQuantity*row.price*100)/100
      }

    this.getEstimatedCost(this.productList2)
    },
    getTotalPrice2(row){
      if(row.price!=null&&row.price!=''&&row.productQuantity!=null&&row.productQuantity!=''){
        row.totalPrice = Math.round(row.productQuantity*row.price*100)/100
      }
      this.getEstimatedCost(this.productList)
    },
    getEstimatedCost(list){
      let estimatedCost = 0;
      list.forEach(obj => {
        if (obj.totalPrice) {
          estimatedCost += obj.totalPrice;
        }
      })
      this.form.estimatedCost = estimatedCost;
      this.form.estimatedCost2=(Math.round(this.form.estimatedCost*100)/100).toFixed(2)
    },

    outsourceTypeChange(){
      this.productList=[];
      this.productList2=[];
      this.form.estimatedCost=null;
      this.form.estimatedCost2=null;
      this.activeTab2='first'
    },
    cancelSelectProduct(){
      this.showFlag=false;
    },
    selectPlanProduct(){
      this.showFlag=true;
    },

    selectLine(row) {
      row.updateStatus = true;
      let t = {};
      t = copyValues(row, t)
      t.planlineId = row.id;
      t.id = null;
      this.orderLine.push(t);
    },

    handleExecute(row) {
      const that = this;
      this.$modal.confirm('是否执行订单？执行订单后将生成工单！').then(function () {
        executeOrder({orderCode: row.orderCode, orderId: row.orderId}).then(response => {
          that.$modal.msgSuccess("操作成功");
          that.open = false;
          that.getList();
        });
      });
    },
    // 获取文件名称
    getFileName(name) {
      if (name && name.lastIndexOf("/") > -1) {
        return name.slice(name.lastIndexOf("/") + 1);
      } else {
        return "";
      }
    },

    refreshOrderLine(orderLine) {
      this.orderLine = orderLine;
      let estimatedCost = 0;
      orderLine.forEach(obj => {
        if (obj.totalPrice) {
          estimatedCost += obj.totalPrice;
        }
      })
      this.form.estimatedCost = estimatedCost;
    },
    // 上传成功
    handleUploaded(data) {
      this.form.drawUrl = data;
    },
    // 删除文件
    handleRemoved(data) {
      this.form.drawUrl = data;
    },
    onManufactureSelected(row) {
      if (row != undefined && row != null) {
        this.form.manufactureId = row.manufactureId;
        this.form.manufactureCode = row.manufactureCode;
        this.form.manufactureName = row.manufactureName;
        this.form.contact = row.contact1;
        this.form.contactTel = row.contact1Tel;
      }
    },
    onProductSelected(list){
      debugger
      this.productList.push(...list);
      if(this.form.outsourceType=='G') {
        this.productList.forEach((item)=>{
          item.price=0.01;
          item.totalPrice=Math.round(item.price * item.productQuantity*100)/100;
        })
      }
    },

    handleDeleteLine(row){
      if(row.id) {
        this.needAddProductList.set(row.planlineId, row);
      }
      this.productList=this.productList.filter(obj => obj.planlineId != row.planlineId)

    },
    handleManufactureSelect() {
      this.manufacture.manufactureId = this.form.manufactureId;
      this.$refs.mfSelect.showFlag = true;
      this.$refs.mfSelect.getList();
    },
    /** 查询订单列表 */
    getList() {
      this.loading = true;
      listOrder(this.queryParams).then(response => {
        this.orderList = response.rows;

        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        orderCode: null,
        orderName: null,
        deadline: null,
        manufactureId: null,
        manufactureCode: null,
        manufactureName: null,
        contact: null,
        contactTel: null,
        paymentType: null,
        status: 0,
        remarks: null,
        estimatedCost: null,
        estimatedCost2: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        drawUrl: null,
        tenantId: null,
        sourceCode: null,
        planNo: null,
        requestDate: null,
        userId: null,
        buyer: null,
        deptId: null,
        buyerDept: null,
        outsourceType:'Z'
      };
      this.resetForm("form");
      this.oldWorkorderId = null;
      this.pictureList = [];
      this.planLineList = [];
      this.productList = [];
      this.productList2 = [];
      this.activeTab = '订单信息'
     this.activeTab2='first'
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      genCode('OUTSOURCE_ORDER_CODE').then(response => {
        this.form.orderCode = response;
      });
      this.open = true;
      this.optType = "save"
      this.planLineOptType = 'select';
      this.title = "添加订单";

    },
    getOrderById(row, title, optType) {
      this.reset();
      const id = row.orderId;
      getOrder(id).then(response => {
        this.form = response.data;
        if(this.form.estimatedCost){
          this.form.estimatedCost2=(Math.round(this.form.estimatedCost*100)/100).toFixed(2)
        }
        this.open = true;
        this.title = title;
        if (this.form.drawUrl) {
          this.pictureList.push(this.form.drawUrl);
        }
        if (this.form.instanceId) {
          approveFlow(this.form.instanceId).then(re => {
            this.approveFlow = re.data.map(item => {
              const updateTime = item.updateTime;
              if (updateTime) {
                const date = new Date(updateTime);
                if (!isNaN(date.getTime())) {
                  item.updateTime = date.toISOString().slice(0, 19).replace('T', ' ');
                } else {
                  item.updateTime = '';
                }
              } else {
                item.updateTime = '';
              }
              return item;
            });
            listApproveOrder(this.form.instanceId).then(response => {
              this.imgUrl = "data:image/gif;base64," + response.data;
            });
          })
        }
        listLine({orderCode: this.form.orderCode}).then(re => {
          if (optType == 'edit') {
            let l = re.rows.map(item => {
              item.updateStatus = true;
              return item;
            })
            this.productList = l;
          } else if (optType == 'confirm' || optType == "view"||optType=='upload') {
            let l = re.rows.map(item => {
              item.updateStatus = false;
              return item;
            })
            this.productList = l;
          }
        })
       /* getPlan(this.form.planId).then(re => {
          this.planLineList = re.data.lineList;
        })*/
      });
    },
    refreshLine(){
      listLine({orderCode: this.form.orderCode}).then(re => {
          let l = re.rows.map(item => {
            item.updateStatus = false;
            return item;
          })
          this.productList = l;
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.planLineOptType = 'select';
      this.optType = "edit"
      this.getOrderById(row, '修改订单', this.optType);

    },
    handleUploadFile(row){
      this.reset();
      this.planLineOptType = 'view';
      this.optType = "upload"
      this.getOrderById(row, '上传附件', this.optType);
    },
    handleInfoView(row) {
      this.planLineOptType = 'view';
      this.optType = "view"
      this.getOrderById(row, '查看订单', this.optType);

    },
    handleInfoConfirm(row) {
      this.planLineOptType = 'view';
      this.optType = "confirm"
      this.getOrderById(row, '确认订单', this.optType);

    },
    confirmOrderFun() {
      if (this.form.orderId != null) {
        const that = this;
        this.$modal.confirm('是否确认订单订单？提交后该订单将无法更改！').then(function () {
          confirmOrder(that.form.orderId).then(response => {
            that.$modal.msgSuccess("操作成功");
            that.open = false;
            that.getList();
          });
        });
      }
    },
    toSaveData(){
      this.form.orderLineList = this.productList;
      if (this.form.orderId != null) {
        updateOrder(this.form).then(response => {
          this.$modal.msgSuccess("修改成功");
          this.open = false;
          this.getList();
        });
      } else {
        addOrder(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.productList.length>0){

            if (this.form.outsourceType=='Z') {
              let checkOrderLine = true;
              if (this.productList2.length > 0) {
                for (let i = 0; i < this.productList2.length; i++) {
                  let item = this.productList2[i];
                  /*if (item.bomId == null) {
                    this.$modal.msgError("请选择" + item.productName + "的产品制程！");
                    checkOrderLine = false;
                    break;
                  }*/
                  this.productList.forEach((p)=>{
                    if(p.productCode==item.productCode){
                      p.price=item.price;
                      p.totalPrice = Math.round(p.productQuantity*p.price*100)/100;
                      this.copy6(item,p)
                    }
                  })
                }
                if (checkOrderLine) {
                  this.toSaveData()
                }
              } else {
                this.$modal.msgError("请进行产品合计！");
              }
            }else{
              //工序外协
              this.toSaveData()
            }
          }else{
            this.$modal.msgError("订单产品不能为空！");
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.orderId || this.ids;
      this.$modal.confirm('是否确认删除订单编号为"' + row.orderCode + '"的数据项？').then(function () {
        return delOrder(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('pro/outsourcingorder/export', {
        ...this.queryParams
      }, `order_${new Date().getTime()}.xlsx`)
    },
    handleSelectUser() {
      this.$refs.userSelect.showFlag = true;
    },
    // 用户选择弹出框
    onUserSelected(obj) {
      if (obj != undefined && obj != null) {
        this.form.userId = obj.userId;
        this.form.buyer = obj.nickName;
        this.form.deptId = obj.dept.deptId;
        this.form.buyerDept = obj.dept.deptName;
      }
    },
  }
};
</script>
<style>
#approveTimeLine .el-timeline-item__node--normal {
  width: 18px;
  height: 18px;
  left: -4px;
}
</style>
